<template>
  <div class="container-box">
    <el-dialog :title="getDialogTitle()" :visible.sync="dialogVisible">
      <el-form v-if="dialogColums.filter(d => d.isForm).length > 0" ref="dialogForm" :model="dialogForm" :rules="rules" label-width="100px">
        <template v-for="(column, index) in dialogColums.filter(d => d.isForm)">
          <el-form-item v-if="column.key === 'store_id'" :key="index" :label="column.title" :prop="column.key">
            <el-select v-model="dialogForm[column.key]" :placeholder="`请选择${column.title}`" style="width: 100%;">
              <el-option v-for="item in list" :key="item.id" :label="item.store_name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item v-else :key="index" :label="column.title" :prop="column.key">
            <el-input v-model="dialogForm[column.key]" :type="column.type" :placeholder="`请输入${column.title}`" />
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onDialogConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { goodsIndex
  // , goodsAdd, updateAttrConfig
} from '../../api/goods';
import { customerAdd, customerDetail, goodsAddCate, goodsCateDetail, goodsCateUpdata } from '../../api/goods';
import curde from '@/mixins/curde'

export default {
  name: 'CateForm',
  mixins: [curde],
  // props: {
  //   id: {
  //     type: String,
  //     default: ''
  //   },
  //   operateType: {
  //     type: String,
  //     default: 'fetch'
  //   }
  // },
  data() {
    return {
      dialogColums: [
        { title: '商品分类', key: 'cat_name', type: 'text', sortable: true, isFilter: false, isTable: true, isForm: true },
        { title: '排序', key: 'sort', type: 'number', sortable: true, isFilter: false, isTable: true, isForm: true },
        { title: '更新时间', key: 'update_time', type: 'text', sortable: true, isFilter: false, isTable: true, isForm: false }
      ],
      list: [],
      saving: false,
      dialogVisible: false,
      rules: {
        company_name: [
          { required: true, message: '请输入单位名称', trigger: ['change', 'blur'] }
          // { required: true, message: '分类名称已存在', validator: cateNameValidator }
        ],
        full_goods_name: [
          { required: true, message: '请输入商品名称-简称', trigger: ['change', 'blur'] }
          // { required: true, message: '分类名称已存在', validator: cateNameValidator }
        ],
        customer_name: [{ required: true, message: '请输入联系人', trigger: ['change', 'blur'] }],
        area: [{ required: true, message: '请输入联系人', trigger: ['change', 'blur'] }],
        company_type: [{ required: true, message: '请选择企业类型', trigger: ['change', 'blur'] }]
      },
      dialogForm: {
        cat_name: '',
        sort: 500
      },
      params: {},
      id: '',
      operateType: '',
    };
  },
  computed: {
    storeHouseDict() {
      return this.$store.getters.storeHouseDict;
    }
  },
  watch: {
    id(val) {
      if (val) {
        // this.getDetail(val);
      }
    }
  },
  created() {},
  methods: {
    getDialogTitle() {
      if (this.operateType === 'add') {
        return '添加分类';
      }
      else if (this.operateType === 'edit' && this.id) {
        return '编辑分类';
      }
      else if (this.operateType === 'fetch' && this.id) {
        return '分类详情';
      }
      else {
        return '分类';
      }
    },
    // table row 样式
    handleRowClass({row, rowIndex}) {
      if (rowIndex === 0) {
        return 'goods_item_row';
      }
      else {
        const preRow = this.list[rowIndex - 1];
        if (preRow.id !== row.id) {
          return 'goods_item_row';
        }
        return '';
      }
    },
    rowDblclick(row, column, event) {
      this.$emit('callback', 'rowDblclick', row);
    },
    // 显示弹框
    showDialog(operateType, params) {
      const { id } = params;
      if (!operateType) {
        this.$message.warning('未知操作');
        return;
      }
      this.id = id;
      this.operateType = operateType;
      if (this.id && ['fetch', 'edit'].includes(this.operateType)) {
        this.getDetail(id);
      }
      this.dialogVisible = true;
    },
    // 关闭弹框
    closeDialog() {
      this.dialogVisible = false;
      this.id = '';
      this.operateType = '';
    },
    // 获取商品数据
    async getData() {
      const { data } = await goodsIndex();
      this.allList = data?.list || [];
      this.handleSpreadList();
      // this.list = data?.list || [];
    },
    // 把商品数据中的规格展开；attrConfig
    handleSpreadList() {
      const allList = this.$json.cloneDeep(this.allList);
      let spreadList = [];
      const socketData = {};
      const goodsSelects = [];  // 存储商品名称
      console.log('allList==', allList);
      allList.forEach(d => {
        // 收集商品名称；
        goodsSelects.push({ label: d.goods_name, value: d.id });

        const attrValue = d.attrValue || [];

        if (attrValue.length > 0) {
          const goodsItem = attrValue.map(attr => {
            const attrItem = Object.assign(d, { attrConfigValue: attr, sku_id: attr.id });
            return this.$json.cloneDeep(attrItem);
          })
          spreadList = spreadList.concat(goodsItem);
        }
        else {
          spreadList.push({ ...d, attrConfigValue: null });
        }
      })
      console.log('spreadList==', spreadList);
      this.spreadList = spreadList;
      this.goodsSelects = goodsSelects;
      this.socketData = socketData;
      this.handleList();
    },
    // 把商品数据中的规格展开；
    handleSpreadList2() {
      const allList = this.$json.cloneDeep(this.allList);
      let spreadList = [];
      const socketData = {};
      const goodsSelects = [];
      allList.forEach(d => {
        // 收集商品名称；
        goodsSelects.push({ label: d.goods_name, value: d.id });

        // 判断商品单规格 ｜ 多规格
        let attrConfig = [];
        if (d?.attrConfig?.config) {
          attrConfig = JSON.parse(d?.attrConfig?.config || '[]')
        }
        // 多规格
        if (attrConfig.length > 0) {
          const goodsItem = attrConfig.map(attr => {
            // socketData[`${d.id}_${attr.sku}`] = attr
            const attrItem = Object.assign(d, { attrConfigValue: attr, sku_id: attr.id });
            return this.$json.cloneDeep(attrItem);
          })
          spreadList = spreadList.concat(goodsItem);
        }
        else {
          spreadList.push({ ...d, attrConfigValue: null });
        }
      })
      this.spreadList = spreadList;
      this.goodsSelects = goodsSelects;
      this.socketData = socketData;
      this.handleList();
    },
    // 展示符合条件的数据
    handleList() {
      this.list = this.filterData(this.spreadList, this.createPayload(this.query));
      console.log('goodsDialog--this.list==', this.list);
      this.paging.total = this.list.length;
    },

    async getDetail(id) {
      try {
        const { data } = await goodsCateDetail({ cat_id: id || this.id });
        this.dialogForm = { ...data };
      } catch(err) {
        console.log('goodsCateDetail--err==', err);
      }
    },
    // dialog 提交；
    async onDialogConfirm() {
      let isValid = false;
      console.log('onDialogConfirm--this.$refs.dialogForm.==', this.$refs.dialogForm);
      this.$refs.dialogForm.validate(valid => {
        console.log('onDialogConfirm--valid==', valid);
        isValid = valid;
      })
      console.log('onDialogConfirm--this.saving ==', this.saving, isValid);
      if (this.saving) return this.$message.error('请勿重复提交');
      if (!isValid) return;
      // this.$message.error('请检查提交内容');

      this.saving = true;
      try {
        const payload = this.$json.cloneDeep(this.dialogForm);
        let res;
        if (this.operateType === 'add') {
          res = await goodsAddCate(payload);
        }
        else {
          res = await goodsCateUpdata(payload)
        }
        console.log('onDialogConfirm--res==', res);
        // console.log('customerAdd--res==', res);
        if (res.data) {
          this.$message({ message: '添加成功', type: 'success' })
          this.$emit('callback', true, res.data);
          this.closeDialog();
        }
        else {
          this.$message({ message: res?.msg || '操作失败', type: 'error' })
        }

        // this.$emit(true, { ...res });
        // if (data && data.length === 2) {
        //   if (data[1]) {
        //     this.getData();
        //     this.$message.success('添加成功')
        //     this.dialogVisible = false;
        //   }
        //   else {
        //     this.$message.error(`添加失败: ${payload.goods_name} ${payload.full_goods_name} 已存在`)
        //   }
        // }
        // else {
        //   this.$message.error(`异常：添加失败`)
        // }
      }
      catch (e) {
        console.log('customerAdd--e==', e);
      }
      this.saving = false;
    },
    // 处理table 单元格显示；
    handleRowResult(item, row) {
      // console.log('handleRowResult--item', item, row, this.storeHouseDict);
      const value = row[item.key] || '';
      if (item.key === 'goods_name' || item.key === 'full_goods_name') {
        const sku = row.attrConfigValue && row.attrConfigValue.sku ? row.attrConfigValue.sku : '';
        return `<strong>${value} ${sku}</strong>`;
      }
      if (item.key === 'stock') {
        const sku = row?.attrConfigValue?.sku;
        if (sku && row?.attrValue && row?.attrValue.length > 0) {
          const skus = row?.attrValue.filter(d => d.sku === sku);
          if (!skus || skus.length === 0) {
            return ''
          }
          return skus.map(d => {
            let skuValue = '';
            if (d.stock && row.unit_name2 && row.unit_convert !== row.unit_convert2) {
              const unitNum = d.stock % row.unit_convert2;
              const unitNum2 = Math.floor(d.stock / row.unit_convert2);
              skuValue = `${unitNum2}${row.unit_name2}${unitNum}${row.unit_name}`
            }
            else {
              skuValue = `${d.stock}${row.unit_name}`
            }
            // let storeHouseName = this.storeHouseDict[d.store_house_id].store_house_name
            let storeHouseName = '';
            return (`${storeHouseName}: ${skuValue}`)
          }).join('\n')
        }

        // const socketKey = `${d.id}_${attr.store_house_id}_${attr.sku}`
        if (row.stock && row.unit_name2 && row.unit_convert !== row.unit_convert2) {
          const unitNum = row.stock % row.unit_convert2;
          const unitNum2 = Math.floor(row.stock / row.unit_convert2);
          return `${unitNum2}${row.unit_name2}${unitNum}${row.unit_name}`
        }
        return `${row.stock}${row.unit_name}`
      }
      // if (item.key === 'cat_id') {
      //   const category = this.goodsCategoryDict[value]
      //   return category?.cat_name || value
      // }
      if (item.key === 'unit_name') {
        return `${row.unit_name} / ${row.unit_name2 || '-'}`
      }
      if (item.key === 'unit_convert') {
        if (row.unit_name2) {
          return `${row.unit_convert2}${row.unit_name} = ${row.unit_convert}${row.unit_name2}`
        }
        return
      }
      return value;
    }
  }
}

</script>
<style lang="scss" scoped>
.container-box {
  padding: 20px;
}
.el-table {
  ::v-deep .goods_item_row {
    background-color: #fdf5e6;
  }
}

.container-box {
  ::v-deep .el-table .cell {
    white-space: pre-line !important;
  }
  .el-pagination {
    margin-top: 10px;
    text-align: right;
  }
}
</style>
